<template>
  <div class="page-content">
    <!--    搜索框-->
    <el-row>
      <el-card style="width: 100%;margin-bottom: 16px">
        <div class="search-box">
          <el-input placeholder="Place input softwareName" v-model:model-value="searchQuery" clearable
                    @keydown.enter="searchSoftware(searchQuery)"
                    @clear="searchSoftware(null)"></el-input>
          <el-button type="primary" @click="searchSoftware(searchQuery)"> 搜索</el-button>
        </div>
      </el-card>
    </el-row>

    <!--内容结构-->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card>

          <el-scrollbar height="calc(100vh - 235px)">
            <div style="margin-top: 6px;margin-bottom: 6px;" class="scrollbar-demo-item"
                 v-for="software in softwareList" :key="software.softwareId"
                 @click="selectSoftware(software)">
              {{ software.softwareName }}
            </div>
          </el-scrollbar>

        </el-card>

      </el-col>
      <el-col :span="16">
        <el-card>
          <div style="height: calc(100vh - 235px);">

            <div v-if="selectedSoftware" style="display: flex; flex-direction: column; height: 100%">
              <div class="software-info-card">
                <el-scrollbar>
                  <div style="display: flex; justify-content: space-between; align-items: end;margin: 0 16px">
                    <div class="software-title">{{ selectedSoftware.softwareName }}</div>
                    <div class="software-price"> 售价区间：{{ selectedSoftware.minPrice }}-{{
                        selectedSoftware.maxPrice
                      }}
                    </div>
                  </div>
                  <p v-if="selectedSoftware.description" class="software-desc">{{ selectedSoftware.description }}</p>

                </el-scrollbar>

              </div>
              <el-table :data="softwareVersionList" style="width: 100%;flex-grow: 1">
                <el-table-column label="软件版本" prop="versionName"/>
                <el-table-column label="系统版本" prop="description"/>
                <el-table-column label="注意事项" prop="remark"/>
                <el-table-column label="更新日期" prop="updateTime">
                  <template #default="{row }">
                    {{ row?.updateTime ? row?.updateTime : row?.createTime }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100px">
                  <template #default="{ row }">
                    <el-button @click="showDialog(row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-empty v-else description="There is no software selected"/>
          </div>
        </el-card>

      </el-col>
    </el-row>


    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <div v-if="selectedVersion">

        <el-table :data="softwareLinkList">
          <el-table-column prop="linkName" align="center" width="100px"/>
          <el-table-column prop="linkUrl" align="start"/>
          <el-table-column align="center" width="50px">
            <template #default="{ row }">
              <el-button :icon="CopyDocument" @click="copyRowData(row)" link/>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onBeforeMount, ref} from 'vue';
import {ElInput, ElButton, ElCard, ElTable, ElTableColumn, ElDialog, ElRow, ElCol, ElMessage} from 'element-plus';
import {CopyDocument} from "@element-plus/icons-vue";
import {getSoftware, getSoftwareLink, getSoftwareVersion} from "@/api/link.ts";
import {Software, SoftwareLink, SoftwareVersion} from "@/type.ts";

const searchQuery = ref('');

const softwareList = ref<Software[]>();
const softwareVersionList = ref<SoftwareVersion[]>();
const softwareLinkList = ref<SoftwareLink[]>();
const selectedSoftware = ref<Software>();
const dialogTitle=ref('CAD')
const selectedVersion = ref<SoftwareVersion>();
const dialogVisible = ref(false);

onBeforeMount(() => {
  searchSoftware('')
})

const searchSoftware = (softwareName: string) => {
  getSoftware(softwareName).then((res) => {
    softwareList.value = res.rows as Software[]
  })
};

const selectSoftware = (software) => {
  selectedSoftware.value = software;
  dialogTitle.value =software.softwareName
  getSoftwareVersion(software.softwareId).then(response => {
    softwareVersionList.value = response.rows as SoftwareVersion[];
  })
};

const showDialog = (version) => {
  selectedVersion.value = version;

  getSoftwareLink({
    softwareId: version.softwareId,
    versionId: version.versionId,
  }).then(response => {
    softwareLinkList.value = response.rows as SoftwareLink[];
  })
  dialogVisible.value = true;
};


const canUseClipboardAPI = () => {
  // 检查浏览器是否支持剪贴板API
  return navigator.clipboard && typeof navigator.clipboard.writeText === 'function';
};


const copyRowData = (row) => {
  const rowString = row.linkUrl
  if (canUseClipboardAPI()) {
    navigator.clipboard.writeText(rowString).then(() => {
      ElMessage.success('Copy Success');
      // 3秒后自动关闭消息
    }).catch((err) => {
      ElMessage.error(err);
    });
  } else {
    fallbackCopy(rowString)
  }

};

const fallbackCopy = (text) => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  // 避免页面滚动
  textArea.style.position = 'fixed';
  textArea.style.top = '-9999px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    const successful = document.execCommand('copy');
    if (successful) {
      ElMessage.success('复制成功');
    } else {
      ElMessage.error('复制失败，请尝试手动复制!')
    }
  } catch (err) {
    console.error('回退复制失败:', err);
    ElMessage.error('复制失败，请尝试手动复制!')
  }
  document.body.removeChild(textArea);
};

</script>

<style scoped>

.page-content {
  width: 70%;
  height: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.search-box {
  width: 100%;
  height: 100%;
  display: flex;
  gap: 10px;
  flex-direction: row;
}


.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background-color: #f1f0f0;
}

.scrollbar-demo-item:hover {
  background-color: #e5e5e5;
}

.scrollbar-demo-item:active {
  background-color: #e5e5e5;
}


.software-info-card {
  margin-bottom: 10px;
  max-height: 40%;
  border-radius: 8px;
  border: #d1d1d1 2px dashed;
  padding: 8px;
  box-shadow: rgba(17, 17, 26, 0.05) 0 4px 16px, rgba(17, 17, 26, 0.05) 0 8px 32px;
}

.version-info-card {
  margin-bottom: 10px;
}

.software-title {
  font-size: 20px;
  font-weight: bold;
}

.software-price {
  font-size: 13px;
  color: #616161;
}

.software-desc {
  text-align: start;
  margin: 0 16px;
  text-indent: 2em;
  font-size: 13px
}
</style>
